import { Controller, Get, Post, Files, Fields } from '@midwayjs/core'
import { UploadMiddleware } from '@midwayjs/busboy'
import { readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { randomUUID } from 'node:crypto'

@Controller('/')
export class HomeController {
  @Get('/')
  async home(): Promise<string> {
    return ''
  }

  @Post('/upload', { middleware: [UploadMiddleware] })
  async upload(@Files() files, @Fields() fields) {
    console.log(files, fields)

    const path = []

    files?.forEach((file: any) => {
      writeFileSync(resolve('public', file.filename), readFileSync(file.data))
      path.push(`/public/${randomUUID()}_${file.filename}`)
    })

    return path
  }
}
